<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    action="string"
    accept="image/jpg,image/jpeg,image/png"
    list-type="picture"
    :on-preview="fileChange"
    :before-upload="onBeforeUploadImage"
    :http-request="UploadImage"
    :file-list="fileList"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件，且不超过500kb（且第一张图片将被设置为封面）</div>
  </el-upload>
</template>

<script>
import { ImportUser, getBase64 } from '@/utils/uploadImage.js'
export default {
  data() {
    return {
      fileList: [],
      list: []
    }
  },
  methods: {
    onBeforeUploadImage(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
      }
      return isIMAGE && isLt1M
    },
    UploadImage(param) {
      // console.log(param)
      // 转base64
      getBase64(param.file).then(res => {
        // 向服务端发送
        ImportUser({ imgMess: res, imgName: param.file.name }).then(res => {
          // console.log(res)
          // 更新图片列表
          this.list.push({ name: param.file.name, url: 'http://1.12.49.243/state/' + res.data })
          // 但是我们上传成功了图片， fileList 里面的值却没有改变，还好有on-change指令可以使用
          param.onSuccess() // 上传成功的图片会显示绿色的对勾
          // 数据上传到状态机整合
          this.$store.commit('datas/imgCatch', this.list)
          return false
        }).catch(response => {
          // console.log('图片上传失败')
          param.onError()
        })
      })
    },
    fileChange(file, fileList) {
      console.log(file, fileList)
      // this.$refs.upload.clearFiles() // 清除文件对象
      this.fileList = [{ name: this.list.name, url: this.list.url }]
    }

  }

}
</script>
